import http from '@/utils/typedHttp';
import {
  type Conversation,
  type ChatMessage,
  MessageSender,
} from '@/types/aiChat';
import { type IssueSeverity, type IssueType } from '@/types/aiCorrector';

// API response types
interface CreateConversationResponse {
  conversation_id: string;
}

interface ChatResponse {
  result: string;
}

interface ConversationListResponse {
  conversation_id: string;
  created_at: string;
}

export const fetchConversationsAPI = async (): Promise<Conversation[]> => {
  try {
    const response = await http.get<ConversationListResponse[]>('/agent/conversations');
    const conversations = response as unknown as ConversationListResponse[];
    return conversations.map((conv) => ({
      id: conv.conversation_id,
      title: '新对话',
      messages: [],
      createdAt: conv.created_at,
      updatedAt: conv.created_at
    }));
  } catch (error) {
    console.error('Failed to fetch conversations:', error);
    throw error;
  }
};

export const createConversationAPI = async (): Promise<Conversation> => {
  try {
    const response = await http.post<CreateConversationResponse>('/agent/conversations');
    const now = new Date().toISOString();

    const createResponse = response as unknown as CreateConversationResponse;
    return {
      id: createResponse.conversation_id,
      title: '新对话',
      messages: [],
      createdAt: now,
      updatedAt: now
    };
  } catch (error) {
    console.error('Failed to create conversation:', error);
    throw error;
  }
};

export const sendMessageAPI = async (
  conversationId: string,
  content: string
): Promise<ChatMessage> => {
  try {
    const response = await http.post<ChatResponse>(`/agent/conversations/${conversationId}/chat`, {
      user_input: content
    }, {
      timeout: 0 // 无超时
    });

    const chatResponse = response as unknown as ChatResponse;
    
    return {
      id: Date.now().toString(),
      content: chatResponse.result,
      sender: MessageSender.AI,
      timestamp: new Date().toISOString()
    };
  } catch (error) {
    console.error('Failed to send message:', error);
    throw error;
  }
};

export const deleteConversationAPI = async (conversationId: string): Promise<void> => {
  try {
    await http.delete(`/agent/conversations/${conversationId}`);
  } catch (error) {
    console.error('Failed to delete conversation:', error);
    throw error;
  }
};

// Types for Agent Check API
export interface CheckRequest {
  item_id: string;
  plan_id: string;
  compliance_type: string;
  risk_level?: string;
  compliance_status?: string;
  description: string;
  title: string;
  inspector: string;
}

export interface CheckResponse {
  id: string; // UUID
  item_id: string;
  plan_id: string;
  type: IssueType;
  severity: IssueSeverity;
  description: string;
  suggestion: string;
  title: string;
  originalContent: string;
  originalDescription: string;
}

/**
 * Batch process multiple check requests
 * @param requests Array of check requests to process
 * @returns Promise that resolves to an array of check responses
 */
export const batchCheckAPI = async (requests: CheckRequest[]): Promise<CheckResponse[]> => {
  try {
    return await http.post<CheckResponse[]>('/agent/check', requests, {
      timeout: 0, // 无超时
    });
  } catch (error) {
    console.error('Failed to process batch check:', error);
    throw error;
  }
};
